<?php
// 订单信息
class Controller_Admin_Order extends Controller_Form
{
    public function __construct ($req, $res)
    {
        $this->_form_type = 'order';
        $this->_list_pagesize = 10;
        $this->_no_buttons = TRUE;
        parent::__construct($req, $res);

        $this->_list_where = array(
            array('status', '<', 100),
        );

        $this->_sort_extra_columns = array(
            array('changed', DB::expr('curdate()')),
        );

        $this->_shopId = App_Shop_Manager::currentShopId();
        if ($this->_shopId > 0)
            $this->_list_where[] = array('shopId', '=', $this->_shopId);
    }

	//首页
    public function action_index ()
    {
        $this->action_list();
    }

    
    public function action_list ($page = 1)
    {
        $filter = array();
        $query  = $this->request->query();

        $guider = new Guider;
        $filter['startDay'] = Arr::get($query, 'startDay');
        $filter['stopDay']  = Arr::get($query, 'stopDay');
        $filter['orderNo']  = Arr::get($query, 'orderNo');
        $filter['status']   = Arr::get($query, 'status', -1);
        $filter['shopId']   = Arr::get($query, 'shopId');
        $filter['goodsType']= Arr::get($query, 'goodsType');

        $filter['statusList']    = Order::options_statusList();
        $filter['goodsTypeList'] = Goods::optionsGoodsType();
        $filter['shopList']      = $guider->optionsAllGuiders();

        if ($this->_shopId > 0)
            $filter['shopId'] = $this->_shopId;

        if (empty($filter['startDay']))
            $filter['startDay'] = date("Y-m-d", time() - 86400 * 7);

        if (empty($filter['stopDay']))
            $filter['stopDay'] = date("Y-m-d", time());

        // list_where
        if ($filter['status'] >= 0)
            $this->_list_where[] = array('status', '=', $filter['status']);

        if ($filter['shopId'] > 0)
            $this->_list_where[] = array('shopId', '=', $filter['shopId']);

        if (! empty($filter['goodsType']))
            $this->_list_where[] = array('goodsType', '=', $filter['goodsType']);

        if (! empty($filter['orderNo']))
        {
            $this->_list_where[] = array('orderNo', 'like', '%'.$filter['orderNo'].'%');
        }
        else
        {
            if (! empty($filter['startDay']))
                $this->_list_where[] = array('created', '>=', strtotime($filter['startDay']));

            if (! empty($filter['stopDay']))
                $this->_list_where[] = array('created', '<', strtotime($filter['stopDay']) + 86400);
        }

        $this->template->set('form_include_head_file', $this->_form->include_edit_file());
        $this->template->set('filter', $filter);

        parent::action_list($page);
    }

	//订单修改
	//$nid int 订单id
    public function action_update ($nid)
    {
        $post = $this->request->post();
        if (! empty($post))
        {
            $this->rebuild_post_data($post);
            $this->_form_data = $post;
        }
        else
        {
            $data = Form_Data::detail($this->_form_type, $nid); 
            $this->_form_data = $data;
        }


        parent::action_update($nid);

    }

	//删除订单
    public function action_delete ($nid)
    {
        Order::remove($nid);
        $this->to_url('list');
    }

    // 
    // 订单打印
    // @param   string  $orderNo
    // 
    public function action_print ($orderNO, $param = NULL)
    {        
        $orderDetail = App_Order::detailPrint($orderNO, $param);
        $this->template->set('title', '订单详细');
        $this->template->set('order', $orderDetail);
        $this->template->set_filename("smarty:admin/order/print");
    }

    // 
    // 设置红包订单的快递单号
    // @param   string  $orderNo
    // 
    public function action_setGiftDeliverNo ()
    {        
        $post      = $this->request->post();
        $deliverNo = Arr::get($post, 'deliverNo');
        $orderNo   = Arr::get($post, 'orderNo');
        $uid       = Arr::get($post, 'uid');

        App_Order_Gift::setDeliverNo($orderNo, $uid, $deliverNo);
        $this->request->redirect('/admin/order/detail_tofriends/' . $orderNo);
    }


    // 
    // 修改订单状态
    // @param   string  $orderNo
    // 
    public function action_setStatus ($orderNo)
    {        
        $post = $this->request->post();
        if (empty($post))
        {
            $orderDetail = App_Order::detail($orderNo);
            $moneyRefund = App_Order::getMoneyRefund($orderDetail);
            $statusList  = App_Order::statusAvailable($orderDetail);
            $this->template->set('title', "订单修改状态：$orderNo");
            $this->template->set('order', $orderDetail);
            $this->template->set('statusList', $statusList);
            $this->template->set('moneyRefund', $moneyRefund);
            $this->template->set_filename("smarty:admin/order/status");
        }
        else
        {
            $statusId    = Arr::get($post, 'statusId');
            $deliverNo   = Arr::get($post, 'deliverNo');
            $moneyRefund = (int) (Arr::get($post, 'moneyRefund') * 100);

            if ($statusId == 2)
            {
                App_Order::setOrderDelivered($orderNo, $deliverNo);
            }
            else if ($statusId == 3)
            {
                App_Order::setOrderFinished($orderNo);
            }
            else if ($statusId == 5)
            {
                App_Order::setOrderRefunding($orderNo);
            }
            else if ($statusId == 6)
            {
                try {
                    $orderDetail = App_Order::detail($orderNo);
                    $paymentId   = Arr::get($orderDetail, 'paymentId');
                    if ($paymentId == 1)
                    {
                        if (Payment_Weixin_Refund::order($orderDetail, $moneyRefund))
                        {
                            // 微信实时返回退款状态
                            App_Order::setOrderRefunded($orderNo);
                        }
                    }
                    else if ($paymentId == 2)
                    {
                        $alipay = new Payment_Alipay_Refund();
                        $alipay->addRefundOrder($orderDetail, $moneyRefund);
                    }
                    else
                    {
                        throw new Exception("无效的支付方式");
                    }
                } 
                catch (Exception $e)
                {
                    Kohana::$log->add(Log::ERROR, "订单退款异常: $orderNo: ". $e->getMessage());
                }
            }

            $this->request->redirect('/admin/order/detail/'.$orderNo);
        }
    }

    public function action_user ($uid)
    {
        $this->_form_type = 'order';
        $this->_list_pagesize = 20;
        $this->_no_buttons = TRUE;

        $this->_list_where = array(
            array('status', '!=', 12),
            array('uid', '=', $uid),
        );
        if ($this->_shopId > 0)
            $this->_list_where[] = array('shopId', '=', $this->_shopId);

        $page = $this->request->query('page');
        $page = max(1, $page);
        
        $this->_form = new Form_List($this->_form_type, $this->_list_pagesize, $this);
        $this->template->set('form_content', $this->_form->build_list($this->_list_where, $page));
        $this->template->set_filename('smarty:form/form');

        if ($this->_list_pagesize > 0)
        {
            $total = $this->_form->get_total_size($this->_list_where);
            $this->template->set('pagination', $this->pagination($total, $this->_list_pagesize, 'query_string', 'page'));
        }
        else
        {
            $this->template->set('pagination', '');
        }
    }

    public function action_detail ($nid)
    {
        $orderDetail = Order::detail($nid);
        $log = new Order_Log($nid);
        $orderlog = $log->getLogs();
        $this->template->set('logs', $orderlog);

        if ($orderDetail['orderType'] == 'TOFRIENDS')
            $this->request->redirect('/admin/order/detail_tofriends/' .$orderDetail['orderNo']);

        if ($orderDetail['tuanId'] > 0)
        {
            $this->template->set('tuan', App_Order_Tuan::detail($orderDetail['tuanId']));
            $this->template->set('buyer', User::getUserFromUid($orderDetail['uid'])->getUserInfo());
        }

        $this->template->set('title', '订单详细');
        $this->template->set('order', $orderDetail);
        $this->template->set_filename("smarty:admin/order/detail");
    }

    public function action_detail_tofriends($nid)
    {
        $orderNo     = $nid;
        $orderDetail = App_Order::detail($orderNo);
        $orderGift   = App_Order_Gift::detail($orderNo);
        $moneyRefund = App_Order::getMoneyRefund($orderDetail, $orderGift);

        $this->template->set('title', '红包订单');
        $this->template->set('order', $orderDetail);
        $this->template->set('gift', $orderGift);
        $this->template->set('moneyRefund', $moneyRefund);
        $this->template->set_filename("smarty:admin/order/detail_tofriends");
    }

    public function detail_filter_config_data (& $arr_config)
    {
        //
    }

    private function rebuild_post_data (& $post)
    {
        //
    }

    public function list_filter_data (& $rows)
    {
        foreach ($rows as & $rs)
        {
            // 金额
            
            $rs['moneyTotal']    = '€' .number_format($rs['moneyTotal']/100, 2);
            $rs['moneyTotalRMB'] = '￥'.number_format($rs['moneyTotalRMB']/100, 2);

            // 导游
            $guider = new Guider($rs['shopId']);
            $rs['guiderName']  = $guider->getRealName($rs['shopId']);

            // 游客
            $tourist = new Tourist($rs['uid']);
            $rs['touristName'] = $tourist->getRealName($rs['uid']);

            // 类型
            $rs['goodsType'] = Goods::orderGoodsTypeName($rs['goodsType']);
        }
    }

    public function list_get_data ($offset, $limit)
    {
        return Order::infoList($offset, $limit, $this->_list_where);
    }

    public function actions_by_list_row (& $row, & $menus)
    {
        unset($menus[1]);

        $status = Arr::get($row, 'status', 0);
        if ($status > 0 && $status < 100)
        {
            unset($menus[2]);
        }
        if ($status >= 4 && $status < 6)
        {
            $menus[] = "<a href=\"/admin/refund/detail/{$row['id']}\">退款</a>";
        }
    }
}
